package com.hnqc.zzwxx;

import javax.swing.*;
import javax.swing.border.TitledBorder;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;

public class Server {
    private DefaultListModel dt;
    private JTextArea jta;
    private JTextField jtf_message=new JTextField();
    private JTextField jtf_port=new JTextField("4567");
    private JTextField jtf_max=new JTextField("30");
    private JButton jbt1_start=new JButton("启动");
    private JButton jbt2_stop=new JButton("停止");
    private JButton jbt3_send=new JButton("发送");
    private  List<Socket> list=new ArrayList<Socket>();
    private  List<User> listuser=new ArrayList<User>();
    private ServerSocket ss ;
    String name=null;
    public void createUI() {
        JFrame jf = new JFrame("服务器");
        jf.setBounds(200, 200, 500, 300);
        //1、北边JPanel
        JPanel northPane = new JPanel();
        northPane.setLayout(new GridLayout(1, 6));
        northPane.add(new JLabel("人数上限"));
        northPane.add(jtf_max);
        northPane.add(new JLabel("端口"));
        northPane.add(jtf_port);
        northPane.add(jbt1_start);

        jbt2_stop.setEnabled(false);
        northPane.add(jbt2_stop);
        northPane.setBorder(new TitledBorder("配置信息"));
        //2、中间JPanel（分左右两栏）
        //左栏
        dt=new DefaultListModel();
        final JList jl=new JList(dt);
        JScrollPane leftpane=new JScrollPane(jl);
        leftpane.setBorder(new TitledBorder("在线用户"));
        //右栏
        jta=new JTextArea();
        jta.setEditable(false);
        JScrollPane rightpane =new JScrollPane(jta);
        rightpane.setBorder(new TitledBorder("消息显示区"));
        JSplitPane centerPane=new JSplitPane(JSplitPane.HORIZONTAL_SPLIT,leftpane,rightpane);
        //设置分隔条的大小
        centerPane.setDividerSize(20);
        //设置分隔条的位置
        centerPane.setDividerLocation(100);
        //3、南部JPanel
        JPanel southPanel=new JPanel(new BorderLayout());
        southPanel.setBorder(new TitledBorder("写消息"));
        southPanel.add(jtf_message,BorderLayout.CENTER);

        jf.setLayout(new BorderLayout());
        jf.add(northPane,BorderLayout.NORTH);
        jf.add(centerPane,BorderLayout.CENTER);
        jf.add(southPanel,BorderLayout.SOUTH);
        jf.setVisible(true);
        jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        serverEvent();

    }

    private void serverEvent() {
        jbt1_start.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                try {
                    ss = new ServerSocket(9999);

                } catch (IOException e1) {
                    e1.printStackTrace();
                }
                new Thread(new Runnable() {//创建线程
                    @Override
                    public void run() {
                        System.out.println("开始监听");
                        //final BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));

                        new Thread(new Runnable() {
                            @Override
                            public void run() {
                                while (true) {
                                    try {
                                        Socket socket = ss.accept();
                                        list.add(socket);
                                        final InputStream inputStream=socket.getInputStream();
                                        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
                                        String s=bufferedReader.readLine();
                                        String[] strings=s.split(",");
                                        String name=strings[0];
                                        String ip=strings[1];
                                        String port=strings[2];
                                        User user=new User(name,ip,port);
                                        listuser.add(user);
                                        dt.addElement(name);
                                        new Thread(new Runnable() {
                                            @Override
                                            public void run() {
                                                while (true){
                                                    try {
                                                        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                                                        String str=bufferedReader.readLine();
                                                        jta.append(str + "\n");
                                                    } catch (IOException e1) {
                                                        e1.printStackTrace();
                                                    }
                                                }
                                            }
                                        }).start();
//                                                final OutputStream out = socket.getOutputStream();
//                                                PrintStream printStream=new PrintStream(out);
                                        //printStream.println(listuser);
                                    } catch (IOException e1) {
                                        e1.printStackTrace();
                                    }

//                                            String str = null;
//                                            try {
//                                                str = bufferedReader.readLine().trim();
//                                                String[] strings= str.split(",");
//                                                String name=strings[0];
//                                                String ip=strings[1];
//                                                String port=strings[2];
//                                                //封装
//                                                User user1=new User(name,ip,port);
//                                                listuser.add(user1);
//                                                dt.addElement(name);
//                                            } catch (IOException e1) {
//                                                e1.printStackTrace();
//                                            }
                                    //jta.append(str + "\n");
                                }
                            }
                        }).start();


                    }
                }).start();

            }
        });

        jtf_message.addKeyListener(new KeyAdapter() {
            @Override
            public void keyPressed(KeyEvent e) {
                if(e.getKeyChar()==KeyEvent.VK_ENTER){
                    for(Socket s:list) {
                        try {
                            PrintWriter pw = new PrintWriter(s.getOutputStream(),true);
                            pw.println(jtf_message.getText());
                            jta.append(jtf_message.getText()+"\n");
                            pw.flush();
                            jtf_message.setText("");
                        } catch (IOException e1) {
                            e1.printStackTrace();
                        }
                    }
                }
            }
        });
    }

    public static void main(String[] args) {
        new Server().createUI();
    }
}



